package com.chenfan.magic.tags;

import com.chenfan.magic.utils.IDKit;
import com.chenfan.magic.utils.StringKit;
import lombok.Data;
import org.apache.commons.lang3.StringEscapeUtils;
import org.jsoup.nodes.Element;

import java.io.Serializable;

/**
 * @author lm
 * redis标签模型
 * <redis key="__USER__"></redis>
 */
@Data
public class TagRedis extends TagAbstract implements Serializable {

    private static final long serialVersionUID = 1L;

    public static String tagNames = "redis";

    protected String cmd;

    /**
     * redis key
     */
    protected String key;
    protected String __key;

    /**
     * redis过期时间, 单位是s
     */
    protected Long expire;
    protected String __expire;

    public TagRedis() {
    }

    public TagRedis(Element redisTag, int index) {
        this.element = redisTag.toString();
        this.id = redisTag.attr("id");
        if (StringKit.isBlank(this.id)) {
            this.id = IDKit.fastUUID() + "";
        }
        this.name = redisTag.attr("name");
        this.key = redisTag.attr("key");
        this.context = StringEscapeUtils.unescapeHtml4(redisTag.text());
        String cmd = redisTag.attr("cmd");
        if (StringKit.isBlank(cmd)) {
            this.cmd = "set";
        } else {
            this.cmd = cmd;
        }
        String sort = redisTag.attr("sort");
        if (StringKit.isBlank(sort)) {
            this.sort = index - 10000;
        } else {
            this.sort = Integer.parseInt(sort);
        }
        this.resultKey = redisTag.attr("result-key");
        if (StringKit.isBlank(this.resultKey)) {
            this.resultKey = "result_" + this.id;
        }
        String respond = redisTag.attr("respond");
        if (StringKit.isBlank(respond)) {
            this.respond = true;
        } else {
            this.respond = Boolean.valueOf(respond);
        }
        String resolve = redisTag.attr("resolve");
        if (StringKit.isBlank(resolve)) {
            this.resolve = true;
        } else {
            this.resolve = Boolean.valueOf(resolve);
        }
        String expire = redisTag.attr("expire");
        if (StringKit.isBlank(expire)) {
            this.expire = 86400L;
        } else {
            this.expire = Long.parseLong(expire);
        }

        this.__sort = redisTag.attr(":sort");
        this.__respond = redisTag.attr(":respond");
        this.__resolve = redisTag.attr(":resolve");
        this.__resultKey = redisTag.attr(":result-key");
        this.__key = redisTag.attr(":key");
        this.__expire = redisTag.attr(":expire");

        this.engine = redisTag.attr("engine");

    }
}
